package controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;

import constant.Msg;
import model.Moment;
import model.User;
import validate.MomentValidate;

public class MomentController extends Controller {
	public void index() {
		int userId;
		String id = getPara("id");
		String sort = getPara("sort");
		String order = getPara("order");
		String content = getPara("content");
		//String images = getPara("images");
		String offset = getPara("offset");
		String length = getPara("length");
		String valid = null;
		switch (getRequest().getMethod()) {
		case "GET":
			String result = Moment.dao.select(sort, order, offset, length);
			if (result == null)
				renderJson(Msg.ERROR_UNKNOWN);
			else
				renderJson(result);
			break;
		case "POST":
			userId = User.userCache.get(getHeader("token"));
			valid = MomentValidate.post(content);
			if (valid != null) {
				renderJson(valid);
				return;
			}
			
			StringBuffer images = new StringBuffer("[");
			while(User.userCache.llen("momentImg"+userId)>0){
				images.append("\""+User.userCache.lpop("momentImg"+userId)+"\"");
				if(User.userCache.llen("momentImg"+userId)>0)
					images.append(",");
			}
			images.append("]");
			if (Moment.dao.add(userId, content, images.toString())) {
				renderJson(Msg.SUCCESS_EXECUTE);
			} else {
				renderJson(Msg.ERROR_UNKNOWN);
			}
			break;
		/*case "PUT":
			valid = MomentValidate.put(id);
			System.out.println(id+"  "+content+"  "+images);
			BufferedReader in;
			String line;
			try {
				in = new BufferedReader(new InputStreamReader(getRequest().getInputStream()));
				while ((line = in.readLine()) != null)
					System.out.println(line);
			} catch (IOException e) {
				e.printStackTrace();
			}
		    
			if (valid != null) {
				renderJson(valid);
				return;
			}
			if (Moment.dao.update(Integer.parseInt(id), content, images)) {
				renderJson(Msg.SUCCESS_EXECUTE);
			} else {
				renderJson(Msg.ERROR_UNKNOWN);
			}
			break;*/
		case "DELETE":
			valid = MomentValidate.delete(id);
			if (valid != null) {
				renderJson(valid);
				return;
			}
			if (Moment.dao.delete(Integer.parseInt(id))) {
				renderJson(Msg.SUCCESS_EXECUTE);
			} else {
				renderJson(Msg.ERROR_UNKNOWN);
			}
			break;
		default:
			renderJson(Msg.SUCCESS_EXECUTE);
		}
	}
	
	public void uploadpic() {
		UploadFile upfile = getFile();
		File file = upfile.getFile();
		String filename = file.getName();
		String delfilename = filename;
		if (filename != null && !filename.equals("")) {
			filename = new SimpleDateFormat("yyyyMMddkkmmss").format(new Date()) + filename;
			User.userCache.lpush("momentImg"+User.userCache.get(getHeader("token")), filename);
			// 新保存的位置
			String path = getRequest().getSession().getServletContext().getRealPath("/");
			String newPath = "/img/";// 自定义目录 用于存放图片
			/**
			 * 没有则新建目录
			 */
			File floder = new File(path + newPath);
			if (!floder.exists()) {
				floder.mkdirs();
			}
			/**
			 * 保存新文件
			 */
			FileInputStream fis = null;
			FileOutputStream fos = null;
			try {
				File savePath = new File(path + newPath + filename);
				if (!savePath.isDirectory())
					savePath.createNewFile();
				fis = new FileInputStream(file);
				fos = new FileOutputStream(savePath);
				byte[] bt = new byte[300];
				while (fis.read(bt, 0, 300) != -1) {
					fos.write(bt, 0, 300);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (null != fis) fis.close();
					if (null != fos) fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			/**
			 * 删除原图片，JFinal默认上传文件路径为 /upload（自动创建）
			 */
			File delFile = new File(path + "/upload/" + delfilename);
			if (delFile.exists()) {
				delFile.delete();
			}
			renderJson(Msg.SUCCESS_EXECUTE);
		} else {
			renderJson(Msg.ERROR_UNKNOWN);
		}
		
	}
	
	public void detail(){
		String id = getPara("id");
		String valid = null;
		int userId = User.userCache.get(getHeader("token"));
		switch (getRequest().getMethod()) {
		case "GET":
			valid = MomentValidate.detail(id);
			if (valid != null) {
				renderJson(valid);
				return;
			}
			renderJson(Moment.dao.selectById(Integer.parseInt(id),userId));
			break;
		default:
			renderJson(Msg.SUCCESS_EXECUTE);
		}
	}
}
